package com.zy.gateway.filtersFactory;

import lombok.extern.java.Log;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Arrays;
import java.util.List;

/**
 * @program: shopping153_cloud
 * @description:
 * @author: zy
 * @create: 2025-08-28 09:03
 */
@Log
@Component
public class MyTimeRateGatewayFilterFactory extends AbstractGatewayFilterFactory<MyTimeRateGatewayFilterFactory.Config> {
    public MyTimeRateGatewayFilterFactory() {
        super(Config.class);
    }
    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {

            long startTime=System.currentTimeMillis();   //请求进入的时间 (豪秒)

            return chain.filter(exchange).then(
                    Mono.fromRunnable(()->{
                long endTime=System.currentTimeMillis();   //请求离开的时间 (豪秒)
                long timeCost=endTime-startTime;   //请求耗时 (豪秒)

                 if(   "s".equals(config.getUnitName())) {
                    timeCost=timeCost/1000;
                 }else if( "m".equals(config.getUnitName())) {
                    timeCost=timeCost/1000/60;
                 }
               log.info("请求耗时:"+timeCost+config.getUnitName());
            }));
        };
    }
    @Override
    public List<String> shortcutFieldOrder() {
        return Arrays.asList(   "unit", "unitName");
    }
    public static class Config {
        private String unit;
        private String  unitName;

        public String getUnit() {
            return unit;
        }

        public void setUnit(String unit) {
            this.unit = unit;
        }

        public String getUnitName() {
            return unitName;
        }

        public void setUnitName(String unitName) {
            this.unitName = unitName;
        }
    }
}
